import { useState } from 'react';
import { Upload, Button, Modal, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';

// 自定义钩子
function usePDFUpload() {
    const [visible, setVisible] = useState(false);
    const [fileList, setFileList] = useState<any[]>([]);

    const handleUpload = () => {
        setVisible(true);
    };

    const handleCancel = () => {
        setVisible(false);
    };

    const handleOk = () => {
        setVisible(false);
        message.success('PDF上传成功');
    };

    const beforeUpload = (file: any) => {
        // 只允许上传 PDF 文件
        if (file.type !== 'application/pdf') {
            message.error('只能上传 PDF 文件!');
            return false;
        }
        return true;
    };

    const onChange = (info: any) => {
        // 处理文件列表变化
        setFileList(info.fileList);
    };


    // 从后端获取文件列表
    const fetchFileList = async () => {
        try {
            const response = await fetch('YOUR_BACKEND_API_URL'); // 替换为你的后端 API URL
            const data = await response.json();
            setFileList(data); // 假设后端返回的文件列表数据结构与 fileList 一致
        } catch (error) {
            message.error('获取文件列表失败');
        }
    };

    return {
        visible,
        handleUpload,
        handleCancel,
        handleOk,
        beforeUpload,
        onChange,
        fileList,
    };
}

const UploadPDF: React.FC = () => {
    const {
        visible,
        handleUpload,
        handleCancel,
        handleOk,
        beforeUpload,
        onChange,
        fileList,
    } = usePDFUpload();

    return (
        <div>
            <Button type="primary" onClick={handleUpload}>
                <UploadOutlined /> 查看/上传
            </Button>
            <Modal title="上传PDF" visible={visible} onOk={handleOk} onCancel={handleCancel}>
                <Upload
                    action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                    listType="text"
                    beforeUpload={beforeUpload}
                    onChange={onChange}
                    fileList={fileList}
                    accept=".pdf" // 限制只能上传 PDF 文件
                >
                    <Button icon={<UploadOutlined />}>点击上传</Button>
                </Upload>
            </Modal>
        </div>
    );
};


export default UploadPDF;